<template>
  <div class="event-list-container">
    <div class="page-header">
      <h2>活动管理</h2>
      <el-button 
        v-if="userRole === 'admin'" 
        type="primary" 
        @click="handleAddEvent">
        添加活动
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input
        v-model="queryParams.keyword"
        placeholder="请输入关键词搜索"
        clearable
        class="search-input"
        @keyup.enter="handleSearch"
      />
      <el-select 
        v-model="queryParams.status" 
        placeholder="活动状态" 
        clearable 
        class="status-select">
        <el-option label="草稿" value="draft" />
        <el-option label="已上线" value="online" />
        <el-option label="已下线" value="offline" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 活动列表表格 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="eventList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="封面" width="120">
          <template #default="scope">
            <el-image 
              style="width: 100px; height: 60px; border-radius: 8px" 
              :src="getImageUrl(scope.row.cover)"
              fit="cover"
              :preview-src-list="[getImageUrl(scope.row.cover)]"
              loading="lazy"
              @error="handleImageError"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span style="font-size: 12px;">加载失败</span>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="活动名称" min-width="150" />
        <el-table-column prop="location" label="活动地点" width="120" />
        <el-table-column label="活动状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" class="status-tag">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div class="button-group">
              <el-button
                type="primary"
                size="small"
                @click="viewEventDetail(scope.row.id)"
              >
                查看
              </el-button>
              <el-button
                v-if="userRole === 'admin'"
                type="success"
                size="small"
                @click="editEvent(scope.row.id)"
              >
                编辑
              </el-button>
              <el-button
                v-if="userRole === 'admin'"
                type="danger"
                size="small"
                @click="confirmDeleteEvent(scope.row.id)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { getEventList, deleteEvent } from '@/api/event'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Search, Plus, Delete, View, Edit, Picture } from '@element-plus/icons-vue'
import { getFullImageUrl, addCacheBuster, parseImageData, handleExternalUploads } from '@/utils/imageHelper'

// 路由实例
const router = useRouter()
// 用户存储
const userStore = useUserStore()
// 获取用户角色
const userRole = computed(() => userStore.role)

// 加载状态
const loading = ref(false)
// 活动列表数据
const eventList = ref([])
// 总记录数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  status: '',
  creatorId: ''
})

// 获取带有缓存破坏参数的图片URL
const getImageUrl = (url) => {
  if (!url) return '';
  
  // 处理不同格式的图片路径
  let imgPath = url;
  
  // 将所有路径格式转换为/images/格式
  if (imgPath.startsWith('/uploads/images/') || imgPath.includes('/uploads/images/')) {
    // 如果是/uploads/images/格式，提取文件名转换为/images/格式
    const filename = imgPath.split('/').pop();
    imgPath = `/images/${filename}`;
  } else if (!imgPath.startsWith('/images/') && !imgPath.startsWith('http')) {
    // 如果不是/images/格式且不是完整URL
    if (imgPath.includes('/')) {
      // 如果包含路径分隔符，提取文件名
      const filename = imgPath.split('/').pop();
      imgPath = `/images/${filename}`;
    } else {
      // 如果只是文件名
      imgPath = `/images/${imgPath}`;
    }
  }
  
  // 确保路径以/开头
  if (!imgPath.startsWith('http') && !imgPath.startsWith('/')) {
    imgPath = `/${imgPath}`;
  }
  
  // 构建完整URL并添加缓存破坏参数
  const API_BASE_URL = 'http://localhost:8089';
  const fullUrl = imgPath.startsWith('http') ? imgPath : `${API_BASE_URL}${imgPath}`;
  
  return addCacheBuster(fullUrl);
}

// 页面加载时获取活动列表
onMounted(() => {
  getEvents()
})

// 获取活动列表
const getEvents = async () => {
  loading.value = true
  try {
    const res = await getEventList(queryParams)
    if (res.code === 200) {
      eventList.value = res.data.records || res.data.list || res.data
      total.value = res.data.total || res.data.length || 0
    } else {
      ElMessage.error(res.msg || '获取活动列表失败')
    }
  } catch (error) {
    console.error('获取活动列表异常:', error)
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 获取状态对应的Tag类型
const getStatusType = (status) => {
  switch (status) {
    case 'draft': return 'info'
    case 'online': return 'success'
    case 'offline': return 'danger'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'draft': return '草稿'
    case 'online': return '已上线'
    case 'offline': return '已下线'
    default: return '未知'
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1 // 重置到第一页
  getEvents()
}

// 重置搜索
const resetSearch = () => {
  queryParams.keyword = ''
  queryParams.status = ''
  handleSearch()
}

// 页码改变
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getEvents()
}

// 每页条数改变
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  queryParams.pageNum = 1 // 重置到第一页
  getEvents()
}

// 查看活动详情
const viewEventDetail = (id) => {
  router.push(`/event/detail/${id}`)
}

// 添加活动
const handleAddEvent = () => {
  router.push('/event/create')
}

// 编辑活动
const editEvent = (id) => {
  router.push(`/event/edit/${id}`)
}

// 确认删除活动
const confirmDeleteEvent = (id) => {
  ElMessageBox.confirm('确定要删除这个活动吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      const res = await deleteEvent(id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getEvents() // 重新加载活动列表
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除活动异常:', error)
      ElMessage.error('删除失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 取消删除，不执行任何操作
  })
}

// 处理图片加载错误
const handleImageError = (e) => {
  console.log('列表项图片加载失败')
  // 不进行重试，避免死循环
}
</script>

<style scoped>
.event-list-container {
  padding: 20px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 32px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0;
  letter-spacing: -0.5px;
}

.page-header .el-button {
  border-radius: 8px;
  font-weight: 500;
  padding: 8px 16px;
  height: auto;
  box-shadow: 0 4px 12px rgba(94, 92, 230, 0.2);
  color: #ffffff;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  background: #fbfbfd;
  padding: 20px;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-container .search-input {
  max-width: 240px;
}

.search-container .status-select {
  width: 160px;
}

.search-container .el-button {
  border-radius: 8px;
  height: 40px;
  font-weight: 500;
}

.search-container .el-button[type="primary"] {
  background: var(--primary-color);
  border-color: var(--primary-color);
  color: #ffffff;
}

.search-container .el-button:not([type="primary"]) {
  color: var(--primary-color);
  border-color: var(--primary-color);
  background: rgba(94, 92, 230, 0.05);
}

.search-container :deep(.el-input__wrapper) {
  background: rgba(0, 0, 0, 0.03);
  border: none;
  box-shadow: none !important;
  border-radius: 10px;
}

.search-container :deep(.el-input__wrapper:hover) {
  background: rgba(0, 0, 0, 0.05);
}

.search-container :deep(.el-select .el-input__wrapper) {
  background: rgba(0, 0, 0, 0.03);
  border: none;
  box-shadow: none !important;
  border-radius: 10px;
}

.table-card {
  background: #fbfbfd;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin-bottom: 24px;
}

.event-list-container :deep(.el-table) {
  border-radius: 0;
  overflow: hidden;
  box-shadow: none;
  border: none;
  background: transparent;
}

.event-list-container :deep(.el-table__header) {
  background-color: #f5f5f7;
}

.event-list-container :deep(.el-table__header th) {
  background-color: #f5f5f7;
  color: #1d1d1f;
  font-weight: 600;
  font-size: 14px;
  height: 54px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

/* 表格行交替颜色 */
.event-list-container :deep(.el-table__row--striped) td {
  background-color: rgba(94, 92, 230, 0.02);
}

/* 表格行悬停效果 */
.event-list-container :deep(.el-table__row:hover) td {
  background-color: rgba(0, 0, 0, 0.02);
}

.pagination-container {
  margin-top: 24px;
  padding: 16px 24px;
  display: flex;
  justify-content: flex-end;
  background-color: #fbfbfd;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.pagination-container :deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: var(--primary-color);
}

.pagination-container :deep(.el-pagination.is-background .el-pager li) {
  border-radius: 50%;
  margin: 0 4px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100px;
  height: 60px;
  background-color: rgba(0, 0, 0, 0.03);
  color: #909399;
  font-size: 14px;
  border-radius: 8px;
}

/* 活动状态标签样式 */
.status-tag {
  border-radius: 12px !important;
  padding: 0 12px !important;
  height: 24px !important;
  line-height: 24px !important;
  font-size: 12px !important;
  font-weight: 500 !important;
  border: none !important;
}

/* 已上线状态 */
.status-tag.el-tag--success {
  color: #34c759 !important;
  background-color: rgba(52, 199, 89, 0.1) !important;
}

/* 未发布状态 */
.status-tag.el-tag--info {
  color: #8e8e93 !important;
  background-color: rgba(142, 142, 147, 0.1) !important;
}

/* 已结束状态 */
.status-tag.el-tag--warning {
  color: #ff9f0a !important;
  background-color: rgba(255, 159, 10, 0.1) !important;
}

/* 已取消状态 */
.status-tag.el-tag--danger {
  color: #ff375f !important;
  background-color: rgba(255, 55, 95, 0.1) !important;
}

.button-group {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.button-group .el-button {
  padding: 6px 12px;
  font-size: 12px;
  border-radius: 8px;
}

/* 查看按钮 */
.button-group .el-button--primary {
  color: #5e5ce6;
  background-color: rgba(94, 92, 230, 0.1);
  border-color: transparent;
}

.button-group .el-button--primary:hover {
  color: #fff;
  background-color: #5e5ce6;
}

/* 编辑按钮 */
.button-group .el-button--success {
  color: #34c759;
  background-color: rgba(52, 199, 89, 0.1);
  border-color: transparent;
}

.button-group .el-button--success:hover {
  color: #fff;
  background-color: #34c759;
}

/* 删除按钮 */
.button-group .el-button--danger {
  color: #ff375f;
  background-color: rgba(255, 55, 95, 0.1);
  border-color: transparent;
}

.button-group .el-button--danger:hover {
  color: #fff;
  background-color: #ff375f;
}
</style> 